package com.ssy.lingxi.enhance.serviceimpl.process;

import com.querydsl.core.BooleanBuilder;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.enhance.constant.*;
import com.ssy.lingxi.enhance.entity.*;
import com.ssy.lingxi.enhance.handler.async.MessageAsyncService;
import com.ssy.lingxi.enhance.handler.async.OrderAsyncService;
import com.ssy.lingxi.enhance.handler.async.ReportAsyncService;
import com.ssy.lingxi.enhance.handler.jpa.QueryDslUtil;
import com.ssy.lingxi.enhance.model.dto.ExamDTO;
import com.ssy.lingxi.enhance.model.qo.ProduceNoticeOrderQO;
import com.ssy.lingxi.enhance.model.vo.ProduceNoticeOrderListVO;
import com.ssy.lingxi.enhance.repository.InnerWorkflowRecordRepository;
import com.ssy.lingxi.enhance.repository.OuterWorkflowRecordRepository;
import com.ssy.lingxi.enhance.repository.ProduceNoticeOrderDetailRepository;
import com.ssy.lingxi.enhance.repository.ProduceNoticeOrderRepository;
import com.ssy.lingxi.enhance.service.process.ProcessToBeConfirmService;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.report.api.enums.EnhanceProcessOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.contant.ProcessTaskStatusEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 加工能力 - 确认生产通知单(加工企业) - 待确认生产通知单 - 业务实现层
 * @author fhj
 * @date 2020/10/20
 * @version 2.0.0
 */
@Slf4j
@Service
public class ProcessToBeConfirmServiceImpl implements ProcessToBeConfirmService {

    @Resource
    private ProcessFeign processFeign;
    @Resource
    private QueryDslUtil queryDslUtil;
    @Resource
    private ProduceNoticeOrderRepository produceNoticeOrderRepository;
    @Resource
    private ProduceNoticeOrderDetailRepository produceNoticeOrderDetailRepository;
    @Resource
    private InnerWorkflowRecordRepository innerWorkflowRecordRepository;
    @Resource
    private OuterWorkflowRecordRepository outerWorkflowRecordRepository;
    @Resource
    private ReportAsyncService reportAsyncService;
    @Resource
    private OrderAsyncService orderAsyncService;
    @Resource
    private MessageAsyncService messageAsyncService;

    /**
     * 列表
     * */
    @Override
    public Wrapper<PageData<ProduceNoticeOrderListVO>> list(ProduceNoticeOrderQO qo, UserLoginCacheDTO user) {
        //查询表实体 - 生产通知单
        QProduceNoticeOrderDO pno = QProduceNoticeOrderDO.produceNoticeOrderDO;

        //查询条件构造 - 必要条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(pno.processMemberId.eq(user.getMemberId()));
        predicates.and(pno.processRoleId.eq(user.getMemberRoleId()));
        predicates.and(pno.outerStatus.eq(PNOOuterStatusEnum.TO_BE_CONFIRM.getCode()));
        predicates.and(pno.processInnerStatus.in(PNOProcessInnerStatusEnum.getProcessToBeConfirmListStatus()));

        return Wrapper.success(queryDslUtil.getProcessPNOList(qo, pno, predicates));
    }

    /**
     * 审核
     * */
    @Override
    @Transactional
    public Wrapper<Void> exam(ExamDTO dto, UserLoginCacheDTO user) {
        //如果审核不通过时, 校验审核不通过原因是否为空
        if(dto.getStatus().equals(ExamStatusEnum.NO.getCode()) && StringUtils.isBlank(dto.getCause())) {
            return Wrapper.fail(ResponseCode.ENHANCE_VALIDATE_DISAGREE_REASON_CAN_NOT_BE_EMPTY);
        }

        //根据ID获取生产通知单详情
        ProduceNoticeOrderDO produceNoticeOrder = produceNoticeOrderRepository.findById(dto.getId()).orElse(null);
        if(produceNoticeOrder == null) {
            return Wrapper.fail(ResponseCode.ENHANCE_BY_ID_NOT_FOUND_PNO);
        }
        if(!(produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.TO_BE_PROCESS_CONFIRM.getCode())
                || produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.PROCESS_SUBMIT_NOT_PASSED.getCode())
                || produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.PROCESS_NOT_PASSED1.getCode())
                || produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.PROCESS_NOT_PASSED2.getCode()))) {
            return Wrapper.fail(ResponseCode.ENHANCE_ONLY_EXAM_INNER_STATUS_AS_TO_BE_PROCESS_CONFIRM_AND_PROCESS_NOT_PASSED);
        }
        if(!produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.TO_BE_PROCESS_CONFIRM.getCode()) && dto.getStatus().equals(ExamStatusEnum.YES.getCode())) {
            return Wrapper.fail(ResponseCode.ENHANCE_ONLY_ACCEPT_EXAM_PASSED);
        }

        //如果通知单来源为加工订单且审核是不通过的话, 需要更新订单服务里的订单商品已加工数量（根据生产通知单明细将新增时加上去的已加工数量再减回去, 保持数量一致性）
        if(produceNoticeOrder.getSource().equals(SourceEnum.ORDER.getCode()) && dto.getStatus().equals(ExamStatusEnum.NO.getCode())) {
            List<ProduceNoticeOrderDetailDO> details = produceNoticeOrderDetailRepository.findByProduceNoticeOrderId(dto.getId());
            orderAsyncService.updateOrderProductProcessNum(details, Boolean.FALSE);
        }

        //调用工作流服务 -> 执行加工企业内部流程
        TaskExecuteVO taskExecuteVO = new TaskExecuteVO();
        taskExecuteVO.setMemberId(produceNoticeOrder.getProcessMemberId());
        taskExecuteVO.setRoleId(produceNoticeOrder.getProcessRoleId());
        taskExecuteVO.setDataId(produceNoticeOrder.getId());
        taskExecuteVO.setTaskId(produceNoticeOrder.getProcessInnerTaskId());
        taskExecuteVO.setAgree(dto.getStatus());
        taskExecuteVO.setProcessKey(produceNoticeOrder.getProcessInnerProcessKey());
        Wrapper<SimpleTaskCompleteVO> processWrapper = processFeign.completeSimpleTask(taskExecuteVO);
        if(ResponseCode.SUCCESS.getCode() == processWrapper.getCode()) {
            //记录加工企业内部工作流记录
            InnerWorkflowRecordDO innerWorkflowRecord = new InnerWorkflowRecordDO();
            innerWorkflowRecord.setProduceNoticeOrderId(produceNoticeOrder.getId());
            innerWorkflowRecord.setUserId(user.getUserId());
            innerWorkflowRecord.setMemberId(user.getMemberId());
            innerWorkflowRecord.setRoleId(user.getMemberRoleId());
            innerWorkflowRecord.setType(RoleTypeEnum.PROCESS.getCode());
            innerWorkflowRecord.setStep(produceNoticeOrder.getProcessInnerStatus());
            innerWorkflowRecord.setOperator(user.getUserName());
            innerWorkflowRecord.setDepartment(user.getUserOrgName());
            innerWorkflowRecord.setJobTitle(user.getUserJobTitle());
            innerWorkflowRecord.setStatus(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? "接受通知单" : "不接受通知单");
            innerWorkflowRecord.setOperate("确认生产通知单");
            innerWorkflowRecord.setOperateTime(System.currentTimeMillis());
            innerWorkflowRecord.setOpinion(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? "接受通知单" : "不接受通知单");
            innerWorkflowRecordRepository.saveAndFlush(innerWorkflowRecord);

            //记录外部工作流记录
            OuterWorkflowRecordDO outerWorkflowRecordDO = new OuterWorkflowRecordDO();
            outerWorkflowRecordDO.setProduceNoticeOrderId(produceNoticeOrder.getId());
            outerWorkflowRecordDO.setUserId(user.getUserId());
            outerWorkflowRecordDO.setMemberId(user.getMemberId());
            outerWorkflowRecordDO.setRoleId(user.getMemberRoleId());
            outerWorkflowRecordDO.setStep(produceNoticeOrder.getOuterStatus());
            outerWorkflowRecordDO.setRoleName(user.getMemberRoleName());
            outerWorkflowRecordDO.setStatus(produceNoticeOrder.getOuterTaskType().equals(ProcessEnum.PNO_OUTER_VERIFY.getCode()) ? "待新增加工发货单" : "待发货");
            outerWorkflowRecordDO.setOperate("确认生产通知单");
            outerWorkflowRecordDO.setOperateTime(System.currentTimeMillis());
            outerWorkflowRecordDO.setOpinion(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? "接受通知单" : "不接受通知单");
            outerWorkflowRecordRepository.saveAndFlush(outerWorkflowRecordDO);

            //接受通知单
            if(dto.getStatus().equals(ExamStatusEnum.YES.getCode())){
                //调用工作流服务 -> 执行外部流程
                taskExecuteVO = new TaskExecuteVO();
                taskExecuteVO.setMemberId(produceNoticeOrder.getSupplierMemberId());
                taskExecuteVO.setRoleId(produceNoticeOrder.getSupplierRoleId());
                taskExecuteVO.setDataId(produceNoticeOrder.getId());
                taskExecuteVO.setTaskId(produceNoticeOrder.getOuterTaskId());
                taskExecuteVO.setAgree(ProcessTaskStatusEnum.GOTO_NEXT_STEP.getCode());
                taskExecuteVO.setProcessKey(produceNoticeOrder.getOuterProcessKey());
                Wrapper<SimpleTaskCompleteVO> outerWrapper = processFeign.completeSimpleTask(taskExecuteVO);
                if(ResponseCode.SUCCESS.getCode() == outerWrapper.getCode()) {
                    //更新状态、加工企业内部状态（根据工作流类型来更新）
                    if(produceNoticeOrder.getOuterTaskType().equals(ProcessEnum.PNO_OUTER_VERIFY.getCode())) {
                        produceNoticeOrder.setStatus(PNOAllStatusEnum.TO_BE_PROCESS_ADD_DELIVERY.getCode());
                        produceNoticeOrder.setProcessInnerStatus(PNOProcessInnerStatusEnum.TO_BE_ADD_DELIVERY.getCode());
                    }else if(produceNoticeOrder.getOuterTaskType().equals(ProcessEnum.PNO_MANUAL_DELIVERY_OUTER_VERIFY.getCode())) {
                        produceNoticeOrder.setStatus(PNOAllStatusEnum.TO_BE_PROCESS_CONFIRM_DELIVERY.getCode());
                        produceNoticeOrder.setProcessInnerStatus(PNOProcessInnerStatusEnum.TO_BE_CONFIRM_DELIVERY.getCode());
                    }
                    //更新外部状态、外部任务ID
                    produceNoticeOrder.setOuterStatus(outerWrapper.getData().getStatus());
                    produceNoticeOrder.setOuterTaskId(outerWrapper.getData().getTaskId());
                    produceNoticeOrderRepository.saveAndFlush(produceNoticeOrder);
                }else {
                    log.error("执行外部工作流程任务失败, 导致生产通知单的任务ID与工作流服务的任务ID不匹配【异常生产通知单】");
                    log.error("工作流服务异常:" + outerWrapper.getMessage());
                    throw new BusinessException(ResponseCode.ENHANCE_WORKFLOW_ERROR);
                }

            //不接受通知单
            }else {
                //更新审核不通过原因、状态、加工企业内部状态、外部状态
                produceNoticeOrder.setCause(dto.getCause());
                produceNoticeOrder.setStatus(PNOAllStatusEnum.PROCESS_NOT_ACCEPTED.getCode());
                produceNoticeOrder.setProcessInnerStatus(PNOProcessInnerStatusEnum.NOT_ACCEPTED.getCode());
                produceNoticeOrder.setOuterStatus(PNOOuterStatusEnum.UN_ACCEPT.getCode());
                produceNoticeOrderRepository.saveAndFlush(produceNoticeOrder);
            }
        }else {
            log.error("工作流服务异常:" + processWrapper.getMessage());
            throw new BusinessException(ResponseCode.ENHANCE_WORKFLOW_ERROR);
        }

        //调用报表服务、消息服务 -> 新增操作通知、发送系统消息，审核不通过的话不需要发送系统消息（如果调用过程出现异常, 无需回滚, 直接catch打印日志正常返回。）
        if(dto.getStatus().equals(ExamStatusEnum.YES.getCode())) {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_PROCESS.getCode(),
                    EnhanceProcessOperateTypeEnum.TO_BE_ADD_DELIVERY.getCode(),  1L,
                    EnhanceProcessOperateTypeEnum.TO_BE_CONFIRM.getCode(), 1L
            );
            messageAsyncService.sendSystemMessage(produceNoticeOrder.getProcessMemberId(), produceNoticeOrder.getProcessRoleId(),
                    MessageTemplateCode.production_order_handle_process_shipment, Stream.of(produceNoticeOrder.getNoticeNo(), produceNoticeOrder.getSummary()).collect(Collectors.toList())
            );
        }else {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_PROCESS.getCode(),
                    null,  null,
                    EnhanceProcessOperateTypeEnum.TO_BE_CONFIRM.getCode(), 1L
            );
        }

        return Wrapper.success();
    }
}
